﻿using System.IO;
using System.Text;
using System.Web;
using System.Web.Caching;
using DotLiquid;
using DotLiquid.FileSystems;

namespace Framework
{
    public class IncludeFileSystem : IFileSystem
    {
        private readonly Encoding _encoding = Encoding.UTF8;
        public IncludeFileSystem() { }
        public IncludeFileSystem(Encoding encoding)
        {
            _encoding = encoding;
        }
        public string ReadTemplateFile(Context context, string templateName)
        {
            bool isOptional = false; //是否可选
            string templateKey = templateName;
            if (templateName.EndsWith("_optional"))
            {
                isOptional = true;
                templateKey = templateKey.Replace("_optional", "");
            }
            if (templateKey.StartsWith("content_"))
            {
                object keyName = context.Environments[0]["keyName"] ?? Path.GetFileNameWithoutExtension(HttpContext.Current.Request.RawUrl);
                templateKey = keyName + "_" + templateKey;
            }
            object result = HttpContext.Current.Cache[templateKey];
            if (result == null)
            {
                if (isOptional && !TemplateHelper.ContainsKey(templateKey))
                {
                    return string.Empty;
                }
                string path = HttpContext.Current.Server.MapPath(TemplateHelper.GetTemplateUrl(templateKey));
                result = File.ReadAllText(path, _encoding);
                var dependency = new CacheDependency(path);
                HttpContext.Current.Cache.Add(templateKey, result, dependency, Cache.NoAbsoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            }
            return result.ToString();
        }
    }
}
